import axios from 'axios'
//import { Message, MessageBox } from 'element-ui'
import { message } from 'ant-design-vue';

// import Cookies from 'js-cookie'

// 本工程中axios使用，均通过其API构建请求，可参考https://www.kancloud.cn/yunye/axios/234845
const service = axios.create({
  retry: 2,
  baseURL: import.meta.env.VITE_APP_API,
  timeout: 50000, // request timeout,
  retryDelay: 1000
})

// request interceptor
service.interceptors.request.use(
  async request => {
    request.headers['Access-Control-Allow-Origin'] = '*'
    // 后端服务jwt token信息
    // var tmpToken = store.getters.token
    // if (!tmpToken) {
    //   tmpToken = Cookies.get('USER_TOKEN')
    // }
    // if (tmpToken) {
    //   request.headers['Authorization'] = tmpToken.access_token
    // }
    return request
  },
  error => {
    // 请求发生错误
    console.log('request interceptor error') // for debug
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  async response => {
    var config = response.config
    const res = response.data
    console.log(response);
    if(response.request.responseURL.indexOf('metedata') >= 0) {
      return response.data;
    } else {
      if (res.code !== 1 && res.code !== 200) {
        if (res.code === 2 || res.code === 3 || res.code === 500 || res.code === 40003 || res.code === 40001) {
          if (res.message) {
            message.error(
              res.message,
              3
            )
          }
          return Promise.reject('error')
        } else {
          if (res.message) {
            message.success(
              res.message,
              3
            )
          }
          return res
        }
      } else {
        return res.data
      }
    }
  },
  async error => {
    console.info('status error', error)
    if (error && error.response) {
      switch (error.response.status) {
        case 401:// 登陆失效
          error.message = '请联系后台人员处理'
          break
        case 500:
          error.message = (error.response.data.message) // 和后台的约定，从后台读取错误信息展示
          break
      }
    }
    message.error(
      error.message,
      3
    )
    return Promise.reject(error)
  }
)

export default service
